package wells.wellsim.client;

import java.util.Scanner;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import wells.wellsim.model.proto.MessageProto;
import wells.wellsim.model.proto.MessageProto.Message;

public class ClientMain {

	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup(0, new DefaultThreadFactory("cim-work"));
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

			@Override
			protected void initChannel(Channel ch) throws Exception {
				ch.pipeline()
						// 10 秒没发送消息 将IdleStateHandler 添加到 ChannelPipeline 中
						.addLast(new IdleStateHandler(0, 10, 0))

						// 心跳解码
						// .addLast(new HeartbeatEncode())

						// google Protobuf 编解码
						// 拆包解码
						.addLast(new ProtobufVarint32FrameDecoder())
						.addLast(new ProtobufDecoder(MessageProto.Message.getDefaultInstance()))
						//
						// 拆包编码
						.addLast(new ProtobufVarint32LengthFieldPrepender()).addLast(new ProtobufEncoder())
						.addLast(new SimpleChannelInboundHandler<Object>() {

							@Override
							protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
								System.out.println(msg);
							}
						});
			}
		});
		;

		ChannelFuture future = null;
		try {
			future = bootstrap.connect("127.0.0.1", 43456).sync();
		} catch (Exception e) {

			System.err.println("Connect fail!");
		}
		if (future.isSuccess()) {
			System.out.println("启动 cim client 成功");
		}

		Scanner input=new Scanner(System.in);
		while(true) {
			
			System.out.println("input:");
			String str= input.next();

			
			SocketChannel channel = (SocketChannel) future.channel();

			Message msg = MessageProto.Message.newBuilder().setAction(str).build();

			channel.writeAndFlush(msg);
			
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				 e.printStackTrace();
				 break;
			}
		}
		input.close();
	}
}
